<template>
    <main>
        <mdui-top-app-bar>
            <mdui-button-icon @click="quit">
                <SvgIcon :path="mdiChevronLeft" type="mdi" />
            </mdui-button-icon>
            <div style="flex-grow: 1"></div>
            <mdui-button @click="submit">
                <SvgIcon :path="mdiPublish" type="mdi" slot="icon" />
                提交
            </mdui-button>
        </mdui-top-app-bar>
        <div class="cont" ref="cont">
            <div class="itemBox" v-for="(item, index) in words" :key="item._id">
                <div v-for="(itemw, indexw) in item.data" :key="itemw._id" class="word_item_card">
                    <span>{{ itemw.trans }}</span><mdui-text-field style="display: inline-block;" variant="outlined"
                        @keydown="nextF($event, () => {
                            if (indexw === item.data.length - 1 && index === words.length - 1) {
                                submit()
                            }
                        })" v-model="itemw.word" @input="itemw.word = $event.target.value"></mdui-text-field>
                </div>



            </div>
            <!-- <mdui-button full-width style="margin:0 auto;max-width: 700px;margin-top: 20px;margin-bottom: 100px;"
                @click="submit">
                <SvgIcon :path="mdiPublish" type="mdi" slot="icon" />
                提交
            </mdui-button>-->
        </div>
    </main>
</template>

<script setup>
import { onMounted, ref, reactive, watch } from 'vue'
import { useRoute } from 'vue-router'
import { snackbar } from 'mdui/functions/snackbar.js';
import SvgIcon from '@jamescoyle/vue-icon'
import { mdiChevronLeft, mdiPublish } from '@mdi/js'
import { prompt } from "mdui/functions/prompt.js";
import { confirm } from 'mdui/functions/confirm.js';
import { nextF } from '@/assets/helper';
import router from '@/router';
const route = useRoute()
const id = ref(route.params.id)
const words = reactive([]) // 使用 reactive 创建响应式数组
const cont = ref(null)
const title = ref('')
onMounted(() => {
    fetch(`${window.server}/api/get_words`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id: id.value })

    })
        .then(response => response.json())
        .then(data => {
            if (data.message === "Success") {
                console.log(data)
                title.value = data.name
                words.splice(0, words.length) // 清空原有的单词列表
                data.words.forEach(item => {
                    item.data.forEach(item => {

                        item.ans = item.word
                        item.word = ""
                        item.etimes = 0
                    })
                    words.push({
                        _id: item._id,
                        data: item.data
                    })
                })
            } else {
                snackbar({
                    message: data.message || "获取单词失败",
                });
            }
        })
        .catch(error => {
            console.error("请求错误:", error)
            snackbar({
                message: "请求错误，请稍后再试",
            });
        })
});

watch(words, (newValue, oldValue) => {
    console.log(newValue, oldValue);

}, {
    deep: true
})
const inputChange = (data, e, index, indexw) => {
    /* let ipt = e.target.innerText;
     // 去除所有换行
     ipt = ipt.replace(/\n/g, ""); 
     
     if (ipt.length > data.ans.length) {
         return;
     }
     // 以ipt.length分割data.word
     const word = data.ans.substring(0, ipt.length);
     if (word != ipt) {
         console.log(word, ipt);
         words[index].data[indexw].etimes++;
     }
 
     if (words[index].data[indexw].etimes > 5){
         console.log("孩子实在不会了，提醒提醒吧");
         
     }*/

}


const submit = () => {

    let num = 0
    words.forEach(element => {
        element.data.forEach(element => {
            if (element.word == "") {
                num++
            }
        });
    });

    if (num > 0) {
        confirm({
            headline: "你有未填的答案",
            description: "你有" + num + "个单词的答案没有填写，是否继续？",
            confirmText: "确认提交",
            cancelText: "取消",
            onConfirm: saveToLocalStorage,
        });
    } else {
        saveToLocalStorage()
    }

}


const saveToLocalStorage = () => {
    const nowTime = new Date().getTime();
    localStorage.setItem("dic-" + id.value + "-" + String(nowTime), JSON.stringify({ name: title.value, data: words }));
    router.push("/hist/" + "dic-" + id.value + "-" + String(nowTime));
}

const quit = () => {
    confirm({
        headline: "确认退出？",
        description: "你有未提交的内容，是否继续？",
        confirmText: "确认退出",
        cancelText: "取消",
        onConfirm: () => router.back(),
    });
}
</script>

<style lang="css" scoped>
main {
    width: 100%;
    height: 100%;
}

.cont {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    box-sizing: border-box
}

.itemBox {
    width: 100%;
    border-top: solid 1px #ddd;
    border-bottom: solid 1px #ddd;
    padding: 20px;
    padding-top: 10px;
    padding-bottom: 30px;
    box-sizing: border-box;
    max-width: 700px;
    margin: 0 auto;

}

.word_item_card {
    span {
        font-size: 20px;
        font-weight: 600;
        line-height: 60px;
        position: relative;
        display: inline-block;
        transform: translateX(8px);

        &::after {
            content: "";
            position: absolute;
            width: 4px;
            height: 20px;
            background-color: #0061A4;
            left: -8px;
            top: 50%;
            transform: translateY(-50%);
            border-radius: 2px;
        }
    }


}
</style>